<?php defined('SYSPATH') or die('No direct access allowed.');

class Service_Pay_Center
{
    private static $appId = '117275430050101802688802260';
    private static $appSecret = '76a7e488e3012337c5447964eea45f9e';
    private static $pay_url = 'https://pay.stccs.com.cn/api';
    /**
     * 创建订单
     * @param $order_params
     * @return bool|string
     * User: netman
     * Date: 2024/3/8 11:31
     */
    public static function create_pay_order($order_params)
    {
        $params = self::setParam($order_params);
        $method = '/order/create';
        $post_url = self::$pay_url.$method;
        $response = self::http_post($post_url, $params);
        return $response;
    }

    /**
     * @param $order 订单
     * @param $refund_cost
     * @return false|int
     * User: netman
     * Date: 2024/3/8 11:32
     */
    public static function refund_order($order,$refund_cost=0)
    {
        if(empty($order)){
            return false;
        }
        $params = [
            'refundSn' => self::generateSequenceId(),
            'outTradeNo' => $order['ordersn'],
            'amount' => (string)($order['payprice']-$refund_cost),
            'extendInfo' => '在线退款'
        ];
        //退款回调为空,默认不走回调
        $params['notifyUrl'] = Common::get_main_host();
        $tra = json_decode($order['online_transaction_no'],true);
        $sequenceId = $tra['transaction_no'];
        $params = self::setParam($params,$sequenceId);
        $post_url = self::$pay_url.'/order/refund';
        $response = self::http_post($post_url, $params);
        $response = json_decode($response,true);
        $status = 2;
        if($response['status'] && $response['data']['refundStatus'] == 'success'){
            $reason = '已退款到支付原账号';
            $status = 1;
            $bool = 1;
        }else{
            $bool = 0;
            $reason = $response['msg'] ? $response['msg'] : '退款失败';
        }
        Pay_Online_Refund::update_refund_log($order, $status, $params['refundSn'], $reason, 'icbcpay', $refund_cost);//更新退款信息
        return $bool;

    }

    /**
     * 中台支付接口参数处理
     * @param $params
     * @return mixed
     */
    public static function setParam($params,$sequenceId = '')
    {
        //通用参数处理
        $params['appId']      = self::$appId;
        $params['sequenceId'] = (empty($sequenceId) ? self::generateSequenceId() : $sequenceId);
        $params['sign']       = self::getSign($params);

        return $params;
    }

    //签名
    private static function getSign($params)
    {
        ksort($params);
        $str_arr = [];
        foreach ($params as $key=>$val){
            $str_arr[] = $key.'='.trim($val);
        }
        $str = implode('&',$str_arr);
        $str .= self::$appSecret;
        return strtoupper(md5($str));
    }
    //生成sequenceId
    private static function generateSequenceId()
    {
        $charid = strtoupper(md5(uniqid(mt_rand(), true)));
        $hyphen = '';
        $uuid =
            substr($charid, 0, 8).$hyphen
            .substr($charid, 8, 4).$hyphen
            .substr($charid,12, 4).$hyphen
            .substr($charid,16, 4).$hyphen
            .substr($charid,20,12);

        return strtolower($uuid);
    }
    //请求
    private static function http_post($url, $postfields = '')
    {
        St_Log::write('中台支付请求：'.$url,$postfields,'CenterPay.log');
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if (!$postfields) {
            return 'data is null';
        }
        if (is_array($postfields)) {
            $postfields = json_encode($postfields, 320);
        }
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $postfields);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length:' . strlen($postfields),
            'Cache-Control: no-cache',
            'Pragma: no-cache'
        ));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl);
        St_Log::write('中台支付请求响应：',$res,'CenterPay.log');
        curl_close($curl);

        return $res;
    }
}